﻿using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.Domain.Models;
using SC.GridManage.MN.API.Write.Application.Command.Artical;

namespace SC.GridManage.MN.API.Write.Application.Handler.Artical
{
    public class DelArticalHandler : IRequestHandler<DelArticalCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ArticalModel> articalRepo;
        private readonly ILogger<DelArticalHandler> logger;

        public DelArticalHandler(IBaseRepository<ArticalModel> articalRepo,ILogger<DelArticalHandler> logger)
        {
            this.articalRepo = articalRepo;
            this.logger = logger;
        }
        public Task<ApiResult<int>> Handle(DelArticalCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model = articalRepo.GetModelAsync(request.Id).Result;
            if (model == null)
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Error;
                result.Msg = "您要删除的文章不存在!";
                //result.Data = 0;

                return Task.FromResult(result);
            }

            model.IsDeleted = true;
           var r =   articalRepo.UpdateAsync(model).Result;
            if (r > 0)
            {

                logger.LogInformation("删除文章:"+model.Title);
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                result.Msg = "删除文章成功!";
                result.Data = r;
            }
            else
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "删除文章失败!";
                result.Data = r;
            }

            return Task.FromResult(result);
        }
    }
}
